package com.wangp.mywrite.coding.NextGreaterElement;

import java.util.*;

/**
 * @author: wp
 * @date: 2023/4/10 15:14:36
 * @desc:
 **/
public class NextLargerNodes {

    /**
     * Definition for singly-linked list.
     */
    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public int[] nextLargerNodes(ListNode head) {
        if (head == null || head.next == null) {
            return new int[]{0};
        }
        ListNode dummy = new ListNode();
        dummy.next = head;
        int count = 0;
        while (dummy.next != null) {
            count++;
            dummy.next = dummy.next.next;
        }
        dummy.next = head;
        int[] res = new int[count];
        int cur = 0;

        while (dummy.next != null) {
            ListNode next = dummy.next;
            int curVal = next.val;
            while (next.next != null && curVal >= next.next.val) {
                next = next.next;
            }
            if (next.next == null) {
                res[cur++] = 0;
            } else {
                res[cur++] = next.next.val;
            }
            dummy.next = dummy.next.next;
        }
        return res;
    }

    public int[] nextLargerNodesStack(ListNode head) {
        List<Integer> ans = new ArrayList<>();
        Deque<int[]>  stack = new ArrayDeque<>();

        int cur = -1;
        while(head != null){
            ++ cur;
            ans.add(0);
            while(!stack.isEmpty() && head.val > stack.peek()[0]){
                ans.set(stack.pop()[1], head.val);
            }
            stack.push(new int[]{head.val,cur});
            head = head.next;
        }
        int[] arr = new int[ans.size()];
        for (int i = 0; i < ans.size(); i++) {
            arr[i] = ans.get(i);
        }
        return arr;
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(7);
        ListNode node3 = new ListNode(4);
        ListNode node4 = new ListNode(3);
        ListNode node5 = new ListNode(5);

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

//        ListNode node1 = new ListNode(3);
//        ListNode node2 = new ListNode(3);
//        node1.next = node2;

        System.out.println(Arrays.toString(new NextLargerNodes().nextLargerNodesStack(node1)));
    }
}
